//
//  DZMReadView.swift
//  DZMeBookRead
//
//  Created by 邓泽淼 on 2017/5/15.
//  Copyright © 2017年 DZM. All rights reserved.
//

import UIKit

class DZMReadView: UIView {
    
    // MARK: -- 阅读ViewFrame
    
    /* 阅读View的位置
     需要做横竖屏的可以在这里修改阅读View的大小
    阅读View的Frame 以及计算分页的范围
     */
    static var readFrame:CGRect {
        let width = UIScreen.main.bounds.width - 2 * CGFloat.readerSpace._1
        var height = UIScreen.main.bounds.height - 2 * (CGFloat.readerSpace._2)
        if UIScreen.main.bounds.height == 812.0
            || UIScreen.main.bounds.height == 896.0 { // 刘海屏适配
            height -= 44.0 // 头部高度
            height -= 34.0 // 底部高度
        }
        return CGRect(x: 0, y: 0, width: width, height: height)
    }
    
    /// CTFrame
    var frameRef:CTFrame? {
        didSet {
            if self.frameRef != nil {
                self.setNeedsDisplay()
            }
        }
    }
    
    weak var readController:CLReadViewController?
    
    /// 绘制
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let frameRef_ = self.frameRef,let ctx = UIGraphicsGetCurrentContext() else {
            return
        }
        
        // 转换坐标
        ctx.textMatrix = CGAffineTransform.identity
        ctx.translateBy(x: 0, y: self.bounds.size.height)
        ctx.scaleBy(x: 1.0, y: -1.0)
        
        CTFrameDraw(frameRef_, ctx)
        
        // 画图片
        let lines = CTFrameGetLines(frameRef_) as NSArray
        
        let ctLinesArray = lines as Array
        var originsArray = [CGPoint](repeating: CGPoint.zero, count:ctLinesArray.count)
        let range = CFRangeMake(0, 0)
        CTFrameGetLineOrigins(frameRef_,range,&originsArray)

        // 遍历CTRun找出图片所在的CTRun并进行绘制,每一行可能有多个
        for index in 0 ..< lines.count {
            //遍历每一行CTLine
            let line = lines[index]
            
            let runs = CTLineGetGlyphRuns(line as! CTLine) as NSArray
            
            for j in 0 ..< runs.count {
                // 遍历每一个CTRun
                var  runAscent = CGFloat()
                var  runDescent = CGFloat()
                let  lineOrigin = originsArray[index] // 获取该行的初始坐标
                let run = runs[j] // 获取当前的CTRun
                let attributes = CTRunGetAttributes(run as! CTRun) as NSDictionary
                
                let width =  CGFloat( CTRunGetTypographicBounds(run as! CTRun, CFRangeMake(0,0), &runAscent, &runDescent, nil))
                let  runRect = CGRect(x: lineOrigin.x + CTLineGetOffsetForStringIndex(line as! CTLine, CTRunGetStringRange(run as! CTRun).location, nil),y: lineOrigin.y - runDescent,width:  width,height: runAscent + runDescent)
                
                let pathRef = CTFrameGetPath(frameRef_)
                let colRect = pathRef.boundingBox
                let targetRect = runRect.offsetBy(dx: colRect.origin.x, dy: colRect.origin.y);

                if let imagePath = attributes["imagePath"] as? String , !imagePath.isEmpty {
                    if let image = CJImageDownloader.shared.fetchImage(imageUrl: imagePath)?.cgImage {
                        ctx.draw(image, in: targetRect)
                    } else {
                        //下载图片
                        CJImageDownloader.shared.download(imageUrl: imagePath, callBack: { [weak self] in
                            DispatchQueue.main.async {
                                let page = self?.readController?.readOperation.getCurrent(isUpdateFont: true,isSave: true)
                               self?.readController?.reloadController(display:page)
                            }
                        })
                    }
                }
            }
        }
    }
}
